import { createRouter, createWebHashHistory } from 'vue-router'
import { useLoginStore } from '@/stores/login'

const router = createRouter({
  history: createWebHashHistory(),
  routes: [
    {
      path: '/',
      name: 'login',
      component: () => import('@/views/LoginView.vue')
    },
    {
      path: '/home',
      name: 'home',
      component: () => import('@/views/HomeView.vue')
    },
    {
      path: '/factory',
      name: 'factory',
      component: () => import('@/views/FactoryView.vue')
    },
    {
      path: '/brand',
      name: 'brand',
      component: () => import('@/views/BrandView.vue')
    },
    {
      path: '/series',
      name: 'series',
      component: () => import('@/views/SeriesView.vue')
    },
    {
      path: '/type',
      name: 'type',
      component: () => import('@/views/TypeView.vue')
    },
    {
      path: '/model',
      name: 'model',
      component: () => import('@/views/ModelView.vue')
    }
  ]
})

router.beforeEach((to, from, next) => {
  const loginStore = useLoginStore()

  if (to.name === 'login') {
    next()
  } else {
    if (sessionStorage.getItem("token")) {
      next()
    } else {
      router.replace({ name: 'login' })
      loginStore.isLogin = false
    }
  }
})

export default router